package com.x.erp.controller;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


import com.x.erp.model.CarLog;
import com.x.erp.model.vo.DetectionVO;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.dubbo.config.annotation.Reference;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import com.x.erp.model.Detection;
import com.x.erp.model.DetectionImage;
import com.x.erp.rpc.DetectionRpcService;
import com.x.erp.util.ConstantState;
import com.x.framework.controller.BaseController;
import com.x.framework.controller.ResultCode;
import com.x.framework.controller.ResultModel;

import javax.servlet.http.HttpServletRequest;

/**
 * 检测单信息
 */
@RestController
public class DetectionController extends BaseController{

	@Reference
	private DetectionRpcService detectionRpcService;//检测单信息服务

	@Autowired
	private FastFileStorageClient fdfsClient;//文件服务

	/**
	 * 查询检测单信息
	 * @param
	 * @return
	 */
	@RequestMapping(value = "/app/getDetectionList", method = {RequestMethod.POST, RequestMethod.GET})
	public ResultModel getDetectionList(Detection detection) {
		if(detection == null || StringUtils.isEmpty(detection.getDetectUserId())) {
			return new ResultModel(ResultCode.RESULT_FAIL, "检测师ID不能为空！");
		}
		return new ResultModel(ResultCode.RESULT_SUCCESS, "查询成功", detectionRpcService.selectDetectionList(detection));
	}


	/**
	 * 查询检测单列表
	 * @param
	 * @return
	 */
	@RequestMapping(value = "/getDetectionList", method = {RequestMethod.POST, RequestMethod.GET})
	public ResultModel selectDetectionList(Detection detection, DetectionVO detectionVO) {
		if(detection == null || StringUtils.isEmpty(detection.getMarketId())) {
			return new ResultModel(ResultCode.RESULT_FAIL, "marketId不能为空！");
		}
		detection.setDetectionVO(detectionVO);
		return new ResultModel(ResultCode.RESULT_SUCCESS, "查询成功", detectionRpcService.selectDetectionList(detection));
	}


	/**
	 * 查询检测单数量
	 * @param detection
	 * @return
	 */
	@RequestMapping(value = "/getDetectionListNum", method = {RequestMethod.POST, RequestMethod.GET})
	public ResultModel getDetectionListNum(Detection detection, DetectionVO detectionVO) {
		Map<String, Object> res = new HashMap<>();
		detection.setDetectionVO(detectionVO);
		res.put("total", detectionRpcService.selectDetectionNum(detection));
		return new ResultModel(ResultCode.RESULT_SUCCESS, "查询成功", res);
	}

	/**
	 * 根据ID查询检测单信息
	 * @param
	 * @return
	 */
	@RequestMapping(value = "/getDetectionById", method = {RequestMethod.POST, RequestMethod.GET})
	public ResultModel getDetectionById(String detectionId) {
		if(StringUtils.isEmpty(detectionId)) {
			return new ResultModel(ResultCode.RESULT_FAIL, "检测单ID不能为空！");
		}
		Detection detection = new Detection();
		detection.setDetectionId(detectionId);
		detection = detectionRpcService.selectDetection(detection);
		DetectionImage image = new DetectionImage();
		image.setDetectionId(detectionId);
		detection.setDetectionImages(detectionRpcService.selectDetectionImageList(image));
		return new ResultModel(ResultCode.RESULT_SUCCESS, "查询成功", detection);
	}

	/**
	 * 去检测单详情页面
	 * @param detectionId
	 * @return
	 */
	@RequestMapping(value = "/toDetectionDetail", method = {RequestMethod.POST, RequestMethod.GET})
	public ModelAndView toDetectionDetail(String detectionId) {
		ModelAndView view = new ModelAndView("common/error.jsp");
		if(StringUtils.isEmpty(detectionId)) {
			view.addObject("errorMsg", "检测单ID不能为空！");
			return view;
		}
		Detection detection = new Detection();
		detection.setDetectionId(detectionId);
		detection = detectionRpcService.selectDetection(detection);
		if(detection == null) {
			view.addObject("errorMsg", "检测单ID错误！");
			return view;
		}
		DetectionImage image = new DetectionImage();
		image.setDetectionId(detectionId);
		detection.setDetectionImages(detectionRpcService.selectDetectionImageList(image));
		view.setViewName("detection/detection_detail.jsp");
		view.addObject("detection", detection);
		return view;
	}


	/**
	 * 修改检测单信息（派单）
	 * @param detection
	 * @return
	 */
	@RequestMapping(value = "/updateDetection", method = {RequestMethod.POST, RequestMethod.GET})
	public ResultModel updateDetection(Detection detection) {
		if(detection == null || StringUtils.isEmpty(detection.getDetectionId())) {
			return new ResultModel(ResultCode.RESULT_FAIL, "检测单ID不能为空！");
		}
		if(detection.getDetectionState() == null){
			return new ResultModel(ResultCode.RESULT_FAIL, "检测单状态不能为空！");
		}
		if(detection.getDetectionState() != ConstantState.DETECTION_STATE_SEND_ORDER){
			return new ResultModel(ResultCode.RESULT_FAIL, "检测单状态不正确！");
		}
		if(StringUtils.isEmpty (detection.getDetectUserId ())){
			return new ResultModel(ResultCode.RESULT_FAIL, "检测师Id不能为空！");
		}
		if(StringUtils.isEmpty (detection.getCarId ())){
			return new ResultModel(ResultCode.RESULT_FAIL, "车辆Id不能为空！");
		}
		//判断是否已派单
		Detection dectionTemp = new Detection();
		dectionTemp.setDetectionId(detection.getDetectionId());
		dectionTemp = detectionRpcService.selectDetection(dectionTemp);
		if(dectionTemp == null){
			return new ResultModel(ResultCode.RESULT_FAIL, "检测单ID不正确！");
		}
		detection.setDetectionUpdateTime(new Date());
		//该请求为派单请求，数据库检测单状态不为0，返回错误提示
		if(dectionTemp.getDetectionState() != ConstantState.DETECTION_STATE_INITIAL){
			return new ResultModel(ResultCode.RESULT_FAIL, "检测单已派单！");
		}
		detectionRpcService.updateDetection(detection);
		return new ResultModel(ResultCode.RESULT_SUCCESS, "修改成功");
	}


	/**
	 * 修改检测单信息（修改检测师）
	 * @param detection
	 * @return
	 */
	@RequestMapping(value = "/changeDetectUserId", method = {RequestMethod.POST, RequestMethod.GET})
	public ResultModel changeDetectUserId(Detection detection) {
		if(detection == null || StringUtils.isEmpty(detection.getDetectionId())) {
			return new ResultModel(ResultCode.RESULT_FAIL, "检测单ID不能为空！");
		}
		if(detection.getDetectionState() == null){
			return new ResultModel(ResultCode.RESULT_FAIL, "检测单状态不能为空！");
		}
		if(detection.getDetectionState() != ConstantState.DETECTION_STATE_SEND_ORDER){
			return new ResultModel(ResultCode.RESULT_FAIL, "检测单状态不正确！");
		}
		if(StringUtils.isEmpty (detection.getDetectUserId ())){
			return new ResultModel(ResultCode.RESULT_FAIL, "检测师Id不能为空！");
		}
		if(StringUtils.isEmpty (detection.getCarId ())){
			return new ResultModel(ResultCode.RESULT_FAIL, "车辆Id不能为空！");
		}
		//判断是否已派单
		Detection dectionTemp = new Detection();
		dectionTemp.setDetectionId(detection.getDetectionId());
		dectionTemp = detectionRpcService.selectDetection(dectionTemp);
		if(dectionTemp == null){
			return new ResultModel(ResultCode.RESULT_FAIL, "检测单ID不正确！");
		}
		detection.setDetectionUpdateTime(new Date());
		//该请求为修改检测师Id，并且检测单状态不为10，返回错误提示
		if(dectionTemp.getDetectionState() != ConstantState.DETECTION_STATE_SEND_ORDER){
			return new ResultModel(ResultCode.RESULT_FAIL, "检测单状态不是派单中状态，无法修改检测师！");
		}
		detectionRpcService.updateDetection(detection);
		return new ResultModel(ResultCode.RESULT_SUCCESS, "修改成功");
	}

	/**
	 * 上传检测结果
	 * @param detection
	 * @param uploadFile
	 * @return
	 */
	@RequestMapping(value = "/app/uploadResult", method = {RequestMethod.POST})
	public ResultModel uploadResult(Detection detection,
	                                @RequestParam(value = "uploadFile", required = true)CommonsMultipartFile uploadFile, HttpServletRequest request) {
		String source = request.getHeader("source");
		if(detection == null || StringUtils.isEmpty(detection.getDetectionId())) {
			return new ResultModel(ResultCode.RESULT_FAIL, "检测单ID不能为空！");
		}
		if(StringUtils.isEmpty(detection.getDetectUserId())) {
			return new ResultModel(ResultCode.RESULT_FAIL, "检测师ID不能为空！");
		}
		if(detection.getDetectionPrice() == null) {
			return new ResultModel(ResultCode.RESULT_FAIL, "评估价不能为空！");
		}
		if(StringUtils.isEmpty(detection.getCarId())) {
			return new ResultModel(ResultCode.RESULT_FAIL, "车辆ID不能为空！");
		}
		if(uploadFile != null && !uploadFile.isEmpty()) {
			String fileId = null;
			try {
				//上传图片
				fileId = fdfsClient.uploadFile(uploadFile.getInputStream(), "png");
			} catch (Exception e) {
				e.printStackTrace();
				return new ResultModel(ResultCode.RESULT_FAIL, "上传图片出错！");
			}
			//图片不为空，查询图片信息
			DetectionImage detectionImage = new DetectionImage();
			detectionImage.setDetectionId(detection.getDetectionId());
			List<DetectionImage> images = detectionRpcService.selectDetectionImageList(detectionImage);
			if(images != null) {
				//如果已有图片信息，删除已有图片
				for(DetectionImage image1 : images) {
					try {
						//删除操作
						fdfsClient.deleteFile(image1.getDetectionImageUrl());
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
			}
			images = new ArrayList<>();
			detectionImage.setDetectionImageSeq(1);
			detectionImage.setDetectionImageCreateTime(new Date());
			detectionImage.setDetectionImageUrl(fileId);
			images.add(detectionImage);
			detection.setDetectionImages(images);
		}
		detection.setDetectionState(ConstantState.DETECTION_STATE_DETECTED);//修改状态为“已检测”
		detection.setDetectionUpdateTime(new Date());//修改时间
		// 上传成功后，修改车辆状态，记录日志
		CarLog carLog = new CarLog("完成检测", new Date(), detection.getDetectUserId(), detection.getCarId());
		carLog.setCarStateKey("carDetectState");
		carLog.setCarStateValue(ConstantState.CAR_DETECT_STATE_REDETECT_FINISH);
		carLog.setCarLogSource(source);
		detectionRpcService.updateDetectionInfo(detection, carLog);
		return new ResultModel(ResultCode.RESULT_SUCCESS, "修改成功");
	}

}

